package personal.gavin.gtweet.widget
{
	import flash.events.EventDispatcher;
	
	import kono.utils.HashTable;
	
	import mx.controls.Alert;
	
	import personal.gavin.gtweet.event.ProcessXMLFinishEvent;
	import personal.gavin.gtweet.event.StatusManagerUpdateFinishEvent;
	
	public class StatusManager
	{
		public function StatusManager()
		{
		}
		private var _managerDispatcher:EventDispatcher = new EventDispatcher();
		
		private var statuses:HashTable = new HashTable(51);
		private var indexs:Array = new Array();
		private var maxLength:int = 20;
		
		public function getCount():int{
			return indexs.length;
		}
		
		public function getIndexById(_id:Number):int{
			if(!isInById(_id)){
				return -1;
			}
			for(var i:uint=0;i<getCount();i++){
				if(indexs[i] == _id){
					return i;
				}
			}
			return -1;
		}
		
		public function isIn(_status:Status):Boolean{
			return statuses.contains(_status.id);
		}
		
		public function isInById(_id:Number):Boolean{
			return statuses.contains(_id);
		}
		
		private function addStatus(_status:Status):int {
			if (_status == null || _status.id <=0 ){
				return -1;
			}
			if (indexs.length == maxLength){
				var id:int = indexs.shift();
				statuses.remove(id);
			}
			var index:int = indexs.push(_status.id);
			statuses.put(_status,_status.id);
			return index;
		}
		
		public function getStatus(_index:int):Status {
			if(_index-1 > indexs.length || _index < 0 || indexs[_index] == null){
				return null;
			}
			var _status:Status = statuses.remove(indexs[_index]);
			statuses.put(_status, indexs[_index]);
			return _status;
		}
		
		public function getStatusById(id:Number):Status {
			if( ! statuses.contains(id) ) {
				return null;
			}
			var _status:Status = statuses.remove(id);
			statuses.put(_status, id);
			return _status;
		}
		
		/**
		 * update statuses for show 
		 * 
		 */		
		public function updateStatuses(callback:Function):void {
			var _status_util:StatusUtil = new StatusUtil();
			_status_util.getStatusesByName(Setting.username,statusLoaded);
			this._managerDispatcher.addEventListener(StatusManagerUpdateFinishEvent.STATUSMANAGER_UPDATE_FINISHED,
			callback);
		}
		
		private function statusLoaded(e:ProcessXMLFinishEvent):void {
			var _statuses:Statuses = Statuses(e.data);
			if(_statuses.error != null){
				Alert.show(_statuses.error.message);
			} else {
				var result:String = "";
				while (_statuses.length > 0){
					var astatus:Status = _statuses.pop();
					if(!isIn(astatus)){
						addStatus(astatus);
					}
				}
			}
			var _manager_event:StatusManagerUpdateFinishEvent = new StatusManagerUpdateFinishEvent(
			StatusManagerUpdateFinishEvent.STATUSMANAGER_UPDATE_FINISHED);
			this._managerDispatcher.dispatchEvent(_manager_event);
		}
	}
}